from re import compile, search
import urllib
from threading import Thread

from Queue import Queue

from BeautifulSoup import BeautifulSoup

import dpcDBs as dbs


def parseEntryPage( user, resp ):
  soup = BeautifulSoup( resp.text )

  # CHALLENGE DETAILS
  s = soup( "a", { "class" : compile( "v" ) } )[0]
  challengeID = int( str( s['href'].split( '=' )[-1] ) )
  challengeName = str( s.text )
  challengeURL = "http://www.dpchallenge.com/challenge_results.php?CHALLENGE_ID=" + str( challengeID )
  #print challengeID, challengeName, challengeURL

  # ENTRY DETAILS
  s = soup( 'td', { 'id': compile( 'img_container' ) } )
  s = BeautifulSoup( str( s ) )( 'img', {'alt': compile( ".*?" )} )[0]
  entryImageURL = str( s['src'] )
  entryName = str( s['alt'] )
  entryThumbURL = entryImageURL.replace( '/800/', '/120/' )
  entryID = int( search( ".*?Copyrighted_Image_Reuse_Prohibited_(\d+)\.jpg", entryImageURL ).group( 1 ) )
  entryURL = "http://www.dpchallenge.com/image.php?IMAGE_ID=" + str( entryID )
  #print entryID, entryName, entryURL, entryImageURL, entryThumbURL


  # Only add if it already exists
  ch = dbs.challengeTable.selectBy( user = user, challengeID = challengeID )
  if ch.count() == 0:
    entryImage = urllib.urlopen( entryThumbURL ).read()
    entryThumb = urllib.urlopen( entryImageURL ).read()

    # Add it to the DB, should automatically replace the old...
    return dbs.challengeTable( 
      challengeName = challengeName,
      entryID = entryID,
      entryURL = entryURL,
      entryName = entryName,
      entryThumbURL = entryThumbURL,
      entryImageURL = entryImageURL,
      challengeID = challengeID,
      challengeURL = challengeURL,
      entryImage = entryImage,
      entryThumb = entryThumb,
      user = user )

  return ch.getOne()
